const order = require('../../model/Order');
const address = require('../../model/Address');
const product = require('../../model/Product')

const requestBody = {
    addressId: '63d0ef6b36a72443348a3c0d',
    shopId: '63d0eb36c30f0dc1c77651eb',
    shopName: '山姆会员商店',
    isCanceled: false,
    products: [
        {
            id: '63d11c6ef40d7f3462418d8b',
            num: 3
        },
        {
            id: '63d11c6ef40d7f3462418d8e',
            num: 8
        }
    ]
}

!(async () => {
    //获取地址信息
    const Address = await address.findById(requestBody.addressId)
    //获取商品列表
    const pIds = requestBody.products.map(item => item.id);
    const productList = await product.find({
        shopId: requestBody.shopId,
        _id: {
            $in: pIds
        }
    })
    const productListWidthSales = productList.map(p => {
        const id = p._id.toString();
        const filterProducts = requestBody.products.filter(item => item.id === id);
        if (filterProducts.length === 0) {
            throw Error('未找到匹配项');
        }
        return {
            product: p,
            orderSales: filterProducts[0].num
        }
    })
    const orderList = await order.create({
        username: '张三',
        shopId: requestBody.shopId,
        shopName: requestBody.shopName,
        isCanceled: requestBody.isCanceled,
        address: Address,
        products: productListWidthSales
    })
})()